﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Mvc;

using tcm.entity;
using tcm.entity.System;
using tcm.Filters;
using tcm.request.System;
using tcm.utils;

namespace tcm.Controller.SystemManage
{
    [ApiController]//记住这个单词
    [Route("tcm/sysuser")]//记住这个
    public class SysUserController : GCCAPIControllerBase
    {
        private readonly AbsGCCContext _context;
        public SysUserController(AbsGCCContext context) : base(context)
        {
            _context = context;
        }

        /// <summary>
        /// 查询账户列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlist")]
        [TCMAuth(permission: "system:user:list")]
        public DataResponse<List<SysUser>> GetList([FromQuery] SysUserRequest request)
        {
            var dbres = GCCEntrance.DBManager!.LocalDB!.Select<SysUser>()
               .WhereIf(!string.IsNullOrWhiteSpace(request.user_name), item => item.user_name.Contains(request.user_name!))
               .WhereIf(!string.IsNullOrWhiteSpace(request.email), item => item.email.Contains(request.email!))
               .WhereIf(!string.IsNullOrWhiteSpace(request.phone), item => item.phone.Contains(request.phone!))
               .Where(x => x.is_delete==0)
               .Count(out var count)
               .Page(request.PageIndex ?? 1, request.PageSize)
               .OrderByDescending(x => x.create_date)
               .ToList();

            return HandleData(dbres, count);
        }


        /// <summary>
        /// 查询维修人员账户
        /// </summary>
        /// <returns></returns>
        [HttpGet("repair")]
        public DataResponse<List<SysUser>> GetRepairList()
        {
            var dbres = GCCEntrance.DBManager!.LocalDB!.Select<SysUser,SysUserRole,SysRole>()
               .LeftJoin((u, ur, r) => u.id==ur.user_id)
               .LeftJoin((u, ur, r) => ur.role_id==r.id)
               .Where((u, ur, r) => r.role_key==GlobalConstant.RepairRole)
               .Where((u,ur,r) => u.is_delete==0&&u.status==1)
               .Count(out var count)
               .ToList();

            return HandleData(dbres, count);
        }


        /// <summary>
        /// 查询账户详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("{id}")]
        public DataResponse<SysUserView> GetSysUser([FromRoute] long id)
        {
            var user = GCCEntrance.DBManager!.LocalDB!.Queryable<SysUser>().Where(x => x.id==id).First();

            if (user==null)
                return HandleData(new SysUserView());

            var model = new SysUserView()
            {
                email= user.email,
                sex=user.sex,
                phone=user.phone,
                remark=user.remark,
                status=user.status,
                user_name=user.user_name,
                nick_name=user.nick_name,
                id=id
            };
            
            var roles = GCCEntrance.DBManager!.LocalDB!.Select<SysRole, SysUserRole>().Where((r, ur) => r.id==ur.role_id && ur.user_id==user.id && r.is_delete==0).ToList();

            if (roles!=null)
            {
                model.roleIds=string.Join(",", roles.Select(x => x.id).ToList());
            }
            
            return HandleData(model);
        }


        /// <summary>
        /// 添加账户
        /// </summary>
        /// <returns></returns>
        [HttpPost("add")]
        [TCMAuth(permission: "system:user:add")]
        public DataResponse<bool> AddSysUser([FromBody] SysUserDto request)
        {
            var saveRes = false;
            try
            {
               
                if (GCCEntrance.DBManager!.LocalDB!.Queryable<SysUser>().Where(x => x.user_name==request.user_name&&x.is_delete==0).Any())
                {
                    throw new Exception("名称已存在");
                };
                if (GCCEntrance.DBManager!.LocalDB!.Queryable<SysUser>().Where(x => x.nick_name==request.nick_name&&x.is_delete==0).Any())
                {
                    throw new Exception("昵称已存在");
                };

                GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
                {
                    _=request.Create(_context, HttpContext.GetToken());
                    var info = BeanUtils.copy<SysUser, SysUserDto>(request);
                    info.id=request.id;
                    info.user_name = request.user_name;
                    info.nick_name =request.nick_name;
                    info.email =request.email;
                    info.phone =request.phone;
                    info.password =SysHelper.Md5(request.password);
                    info.login_date = DateTime.Now;
                    info.create_date=request.create_date;
                    info.create_by=request.create_by;
                    info.update_by=request.update_by;
                    info.update_date =request.update_date;
                    info.token = string.Empty;

                    if (GCCEntrance.DBManager!.LocalDB!.Insert(info).ExecuteAffrows() != 1)
                    {
                        throw new Exception("保存错误");
                    }
                    saveRes=true;
                });
            }
            catch(Exception exc) {
                return SystemError<bool>(exc.Message);
            }
          

            //更新权限
            if (saveRes)
            {
                SaveRole(request);
            }
      
            return HandleData(saveRes);
        }


        /// <summary>
        /// 保存菜单权限
        /// </summary>
        /// <param name="role_id"></param>
        /// <param name="menuIds"></param>
        private static void SaveRole(SysUserDto request)
        {
            var saveRes = false;

            //删除原角色菜单
            var execute = GCCEntrance.DBManager!.LocalDB!.Delete<SysUserRole>().Where(x => x.user_id==request.id).ExecuteAffrows();
            if (request.id<=0||string.IsNullOrWhiteSpace(request.roleIds))
                return;
            var ids = SysHelper.SpitIntArrary(request.roleIds);

            // 新增用户与角色管理
            List<SysUserRole> sysUserRoles = new List<SysUserRole>();

            //插入新菜单
            foreach (var id in ids)
            {
                sysUserRoles.Add(new SysUserRole()
                {
                    role_id=id,
                    user_id=request.id,
                    create_by=request.update_by,
                    create_date=request.update_date
                });
            }
            if (sysUserRoles.Count>0)
                saveRes = GCCEntrance.DBManager!.LocalDB!.Insert<SysUserRole>(sysUserRoles).ExecuteAffrows()>0;
        }


        /// <summary>
        /// 更新账户
        /// </summary>
        /// <returns></returns>
        [HttpPost("update")]
        //[TCMAuth(permission: "system:user:update")]
        public DataResponse<bool> UpdateSysUser([FromBody] SysUserDto request)
        {
            var saveRes = false;
            if (request.id<=0)
                return SystemError<bool>("id为空");
   
            if (GCCEntrance.DBManager!.LocalDB!.Queryable<SysUser>().Where(x => x.user_name==request.user_name&& x.id!=request.id&&x.is_delete==0).Any())
            {
                return SystemError<bool>("名称已存在");
            };
            if (GCCEntrance.DBManager!.LocalDB!.Queryable<SysUser>().Where(x => x.nick_name==request.nick_name&& x.id!=request.id&&x.is_delete==0).Any())
            {
                return SystemError<bool>("昵称已存在");
            };
            GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
            {
                _=request.Modify(_context,HttpContext.GetToken());
                saveRes = GCCEntrance.DBManager!.LocalDB!.Update<SysUser>(request.id)
                .Set(item => item.email, request.email)
                .Set(item => item.status, request.status)
                .Set(item => item.user_name, request.user_name)
                .Set(item => item.phone, request.phone)
                .Set(item => item.remark, request.remark)
                .Set(item => item.sex, request.sex)
                .Set(item => item.nick_name, request.nick_name)
                .Set(item => item.update_by, request.update_by)
                .Set(item => item.update_date, request.update_date)
                .ExecuteAffrows()==1;
            });

            //更新权限
            if (saveRes)
            {
                SaveRole(request);
            }

            return HandleData(saveRes);
        }


        /// <summary>
        /// 删除账户
        /// </summary>
        /// <returns></returns>
        [HttpDelete("delete/{id}")]
        [TCMAuth(permission: "system:user:remove")]
        public DataResponse<bool> DeleteSysUser([FromRoute] long id)
        {
            var saveRes = false;
            if (id<=0)
                return SystemError<bool>("id为空");
            if (id<=1)
                return SystemError<bool>("不能删除管理员");

            saveRes = GCCEntrance.DBManager!.LocalDB!.Update<SysUser>(id)
            .Set(item => item.is_delete, 1)
            .ExecuteAffrows()==1;

            Logger.Information(String.Format("账号ID：{0}已删除。", id), _context.EventID);
            return HandleData(saveRes);
        }


        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPut("updatePwd")] 
        public DataResponse<bool> UpdatePwd([FromBody] SysUserPwd request)
        {
            if (request.id<=0||string.IsNullOrWhiteSpace(request.password)||string.IsNullOrWhiteSpace(request.new_password))
                return SystemError<bool>("参数不可为空");

            var res = GCCEntrance.DBManager!.LocalDB!.Queryable<SysUser>().Where(x => x.id==request.id).First();
            request.new_password = SysHelper.Md5(request.new_password);
            request.password = SysHelper.Md5(request.password);
            if (res==null||!res.password.Equals(request.password))
                return SystemError<bool>("旧密码不正确");

            _=request.Modify(_context, HttpContext.GetToken());
            return HandleData(GCCEntrance.DBManager!.LocalDB!.Update<SysUser>(request.id)
                           .Set(item => item.password, request.new_password)
                           .Set(item => item.update_by, request.update_by)
                           .Set(item => item.update_date, request.update_date)
                           .ExecuteAffrows()==1);
        }


        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        [HttpPut("resetPwd")]
        [TCMAuth(permission: "system:user:resetPwd")]
        public DataResponse<bool> ResetPwd([FromBody] SysUpdatePwd request)
        {
            if (request.id<=0|| string.IsNullOrWhiteSpace(request.new_password))
                return SystemError<bool>("参数不可为空");
            request.new_password = SysHelper.Md5(request.new_password);
            _=request.Modify(_context, HttpContext.GetToken());

            var bol = GCCEntrance.DBManager!.LocalDB!.Update<SysUser>(request.id)
                           .Set(item => item.password, request.new_password)
                           .Set(item => item.update_by, request.update_by)
                           .Set(item => item.update_date, request.update_date)
                           .ExecuteAffrows()==1;
     

            Logger.Information(String.Format("账号ID：{0}已重置密码。", request.id), _context.EventID);
            return HandleData(bol);
        }


    }
}
